package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.luo.config.JWTInterceptor;
import com.luo.config.Log;
import com.luo.pojo.User;
import com.luo.service.user.UserService;
import com.luo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController

public class LoginController {
    @Autowired
    private UserService userService;

    @Log(logStr = "用户登录，检查token是否有效")
    @PostMapping("/login")
    public String getUser(@RequestParam(value = "user",required = false)String users){
        System.out.println(users);
        JSONObject map = JSON.parseObject(users);
        if(userService.isPwd(map.getString("user"),map.getString("pass"))){
            User user = userService.getUserByNumber(map.getString("user"));
            Map<String,String> m = new HashMap<>();
            m.put("user",user.getUsername());
            String token = JwtUtil.setToken(m);
//            response.setHeader("token", token);
//            response.addHeader("token",JwtUtil.setToken(m));
            System.out.println(token+"请求头");
            //System.out.println(JwtUtil.getUser(JwtUtil.setToken(m)));
            return token;
        }else{
            return null;
        }
    }
    @GetMapping("/getUser")
    public User getUser(HttpServletRequest request,HttpServletResponse response){
        String token  = request.getHeader("token").replace("Bearer ","");
        try{
            String username = JwtUtil.getUser(token);
            User user = userService.getUserByName(username);
                user.setAvatar(user.getAvatar());
            return user;
        }catch (Exception e){
            try{
                response.setHeader("code", Integer.toString((Integer) JWTInterceptor.map.get("code")));
            }catch (Exception e1){
                System.out.println(e1);
            }
            System.out.println(JWTInterceptor.map.get("msg"));
        }
      return null;
    }

}
